#ifndef RANDOM_HPP
#define RANDOM_HPP

#include <cstdlib>
#include <ctime>
#include <climits>
#include <vector>
#include <numeric>
#include "error.hpp"

#define RANDOM_MAX              SHRT_MAX
#define PROBABILITY_SCALE       10000

typedef std::vector < double >  probabilities_v;

class random_c
{
public:
        static random_c & get ( void )
        {
                static random_c instance;
                return instance;
        }
       
        random_c ()
        {
                srand ( time ( NULL ) );
        }

        long next ( long max_value = RANDOM_MAX  )
        {
                return rand () % max_value;
        }

        long wheel_of_fortune ( const probabilities_v & probabilities )
        {
                long    jackpot = next ( PROBABILITY_SCALE );
                long    winner  = 0;
                
                for ( probabilities_v::const_iterator i = probabilities.begin (); i != probabilities.end (); i ++ )
                {
                        double candidate = ( double ) * i + 1.0 / PROBABILITY_SCALE;
                        candidate *= PROBABILITY_SCALE;
                        jackpot -= ( long ) ( candidate + 0.5 );

                        if ( jackpot <= 0 )
                                return winner;
                        else
                                winner ++;
                }

                throw ERROR_STATE_UNEXPECTED;
        }
};

#endif

